package WorkWithFile;

import java.io.*;
import java.util.Scanner;
public class TextFile {

    private static Scanner in;
	private static Scanner input;
	public static void main(String[] args){        
        String t;
        System.out.println("Nhap duong link dan den file: ");
        in = new Scanner(System.in);
        t=in.nextLine();
        System.out.println(DocFile(t));
         System.out.println("Tao noi dung mot file van ban: ");
         String text=in.nextLine();
        System.out.println(GhiFile(t,text,true));
    }
    public static String DocFile(String t){
        try {
            //Tao thuoc tinh file cho t
            FileInputStream fr = new FileInputStream(t);
            //Ma hoa tep tin van ban su dung encode UTF8
            Reader r= new java.io.InputStreamReader(fr, "UTF8");
            BufferedReader br = new BufferedReader(r);
            StringBuilder text = new StringBuilder();
            String line=null;
            while((line=br.readLine())!=null){
                text.append(line + "\n");
            }
            br.close();
            return text.toString();
        }
        catch(Exception e){
            System.out.println("Khong doc duoc file!!! "+t);
        }
        return "";
    }
    public static boolean GhiFile(String s ,String text,boolean a){
        String fileCu="";
        if(!a) fileCu=DocFile(s);
        input = new Scanner(System.in);
            System.out.println("Nhap duong dan den file dau ra: ");
            String w=input.nextLine();
           
        try{
            FileOutputStream fw=new FileOutputStream(w);
            Writer wr=new java.io.OutputStreamWriter(fw, "UTF8");
            wr.write(fileCu+text);
            wr.close();
            return true;
        }
        catch(Exception e){
            System.out.println("Khong the ghi duoc file!!! "+w);
            return false;
        }
    }
}
